package cn.qdu.controller;

import cn.qdu.model.User;
import cn.qdu.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;

@WebServlet("/user/update")
public class UserUpdateServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // 解决请求乱码
        response.setContentType("text/html;charset=UTF-8");  // 解决响应乱码

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/views/auth/login.jsp");
            return;
        }

        try {
            // 获取表单数据
            String nickname = request.getParameter("nickname");
            Date birthDate = request.getParameter("birthDate").isEmpty() ? null : Date.valueOf(request.getParameter("birthDate"));
            String gender = request.getParameter("gender");
            String bio = request.getParameter("bio");

            // 更新用户信息
            User updatedUser = new User();
            updatedUser.setUserId(currentUser.getUserId());
            updatedUser.setNickname(nickname);
            updatedUser.setBirthDate(birthDate);
            updatedUser.setGender(gender);
            updatedUser.setBio(bio);

            if (userService.updateUser(updatedUser)) {
                // 更新session中的用户信息
                User user = userService.getUserById(currentUser.getUserId());
                session.setAttribute("currentUser", user);

                // 重定向回个人资料页，并显示成功消息
                response.sendRedirect(request.getContextPath() + "/views/user/profile.jsp?updateSuccess=true");
            } else {
                request.setAttribute("error", "更新个人信息失败");
                request.getRequestDispatcher("/views/user/profile.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "更新个人信息失败: " + e.getMessage());
            request.getRequestDispatcher("/views/user/profile.jsp").forward(request, response);
        }
    }
}
